package bjtu.cit.bookshop.controller;

import bjtu.cit.bookshop.common.ErrorCode;
import bjtu.cit.bookshop.common.Md5;
import bjtu.cit.bookshop.entities.User;
import bjtu.cit.bookshop.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by jia19 on 2015/9/28.
 */
@Controller
@RequestMapping("/")
public class LoginController extends BaseController {

    @Resource
    private IUserService userService = null;

    /**
     * 登陆界面的展示，将用户是否登陆添加到参数map中
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("login.do")
    public String login(ModelMap model, HttpSession session) {
        String isLogin = (String)session.getAttribute("isLogin");
        if(isLogin != null && isLogin.equals("true")) {
            model.addAttribute("isLogin", true);
            model.addAttribute("loginName", session.getAttribute("loginName"));
            return "alreadyLogin";
        }
        else {
            model.addAttribute("isLogin", false);
        }
        return "login";
    }

    /**
     * 登陆处理方法。判断用户的用户名密码是否匹配。
     * @param request
     * @param session
     * @return
     */
    @RequestMapping("doneLogin.do")
    @ResponseBody
    public ErrorCode doneLogin(HttpServletRequest request, HttpSession session) {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (username != null && password != null)
        {
            password = Md5.getMd5(password);
            User user = userService.getUserByUserName(username);
            if (user != null && user.getPassword().equals(password)){
                session.setAttribute("userId", user.getId());
                session.setAttribute("isLogin", "true");
                session.setAttribute("loginName", username);
                session.setAttribute("admin", "false");
                return SUCCESS;
            }
            else {
                session.setAttribute("isLogin", "false");
                session.setAttribute("loginName", "");
                return BAD_PASSWORD;
            }
        }
        else
        {
            return INFORMATION_MISSING;
        }
    }

    @RequestMapping("logout.do")
    public String logout(HttpSession session) {
        session.setAttribute("isLogin", "false");
        session.setAttribute("loginName", null);

        return "index";
    }

}
